package io.github.iogogogo.provider;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.google.common.collect.Maps;
import io.github.iogogogo.properties.DruidProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by tao.zeng on 2024/11/7.
 */
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class YamlDynamicDataSourceProvider implements DynamicDataSourceProvider {

    private final DruidProperties druidProperties;

    public YamlDynamicDataSourceProvider(DruidProperties druidProperties) {
        this.druidProperties = druidProperties;
    }

    @Override
    public Map<String, DataSource> loadDataSources() {
        Map<String, Map<String, String>> map = druidProperties.getDs();

        Map<String, DataSource> ds = Maps.newHashMap();
        map.forEach((k, v) -> {
            try {
                DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(v);
                ds.put(k, druidProperties.dataSource(dataSource));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return ds;
    }
}
